(function () {
    var Zeditor = function () {
        this._productId = 'page1';
        this._canvasInitWidth = 2000;
        this._canvasInitHeight = 1000;
        this._initRate=this._canvasInitWidth/this._canvasInitHeight;
        this._pageCount = 20;
        this._pageCellGap = 30;
        this._pageMargin = {
            left: 60,
            top: 60,
            bottom: 60,
            right: 60
        }
        this._pageBorder = 7;
        this._canvas = null;
        this._borderScale=2;

        this._moduleCanvasHeight=90;
        this._toModuleRate=this._canvasInitHeight/this._moduleCanvasHeight;

        this._zAllFileInfo = {};
        this._zAllFileInfoToPost = {};
        this._toPostUrl = "http://116.62.9.171:8100/api/nemo/getNemoInfo";

        this._keyNum = 0;
        this._currentModule = 1;
        this._totalModules = null;

        this._currentPageAlgo = null;
        this._currentPageAlgosAll = null;
        this._cpAlgoIndex = 0;
        this._totalModuleAlgos = [];

        this._isDragging = false;
        this._curDragDom = null;
        this._curDragDomUse = null;
        this._curDragDomImg = null;
        this._curDragDomImgId = null;

        this._isCanvasReplace = false;
        this._replaceImg = null;
    }
    Zeditor.prototype = {
        infoToDic: function (array) {
            var self = this;
            var FilesToInfo = {};
            for (var i = 0; i < array.length; i++) {
                var zFileId = array[i].ifaID;
                var zSingleInfo = {};
                zSingleInfo.fileInfo = array[i].source.source;
                // zSingleInfo.imgUrl = URL.createObjectURL(array[i].source.source);
                if (array[i]._meta && array[i]._meta.exif) {
                    zSingleInfo.exifInfo = array[i]._meta.exif;
                }
                zSingleInfo.fileName = array[i].name;
                zSingleInfo.lastModify = array[i].lastModifiedDate;
                zSingleInfo.fileType = array[i].type;
                zSingleInfo.fileSize = array[i].size;
                zSingleInfo.fileHeight = array[i]._info.height;
                zSingleInfo.fileWidth = array[i]._info.width;
                zSingleInfo.thumbSrc = array[i].thumbSrc;
                // zSingleInfo.screenSrc = array[i].screenSrc;

                FilesToInfo[zFileId] = zSingleInfo;
                self._zAllFileInfo[zFileId] = zSingleInfo;
            }
            return FilesToInfo;
        },
        appendToLeft: function (fId, fObj, status) {
            var $tplHTML = $('#tpl_left_item').html();
            if (status) {
                var useNum = 1;
                var useClass = 'useTag1';
            } else {
                var useNum = 0;
                var useClass = 'noUse';
            }
            var $itemHTML = layui.laytpl($tplHTML).render({ num: useNum, cls: useClass, url: fObj.thumbSrc, id: fId });
            $('#LAY_left').append($($itemHTML));
        },
        zAllInfoToPostdata: function (obj) {
            var self = this;
            var postData = {};
            postData.page_width = self._canvasInitWidth;
            postData.page_height = self._canvasInitHeight;
            postData.page_cell_gap = self._pageCellGap;
            postData.page_count = self._pageCount;
            postData.page_margin = self._pageMargin;
            var nodes = [];
            for (var k in obj) {
                var singleFile = {};
                singleFile.id = k;

                if (obj[k].exifInfo && (obj[k].exifInfo[274] == 6 || obj[k].exifInfo[274] == 8 || obj[k].exifInfo[274] == 5 || obj[k].exifInfo[274] == 7)) {
                    singleFile.w = obj[k].fileHeight;
                    singleFile.h = obj[k].fileWidth;
                    // console.log(obj[k].exifInfo[274], '1');

                } else {
                    singleFile.w = obj[k].fileWidth;
                    singleFile.h = obj[k].fileHeight;
                    // console.log(obj[k].exifInfo[274], '2');

                }

                if (obj[k].exifInfo && obj[k].exifInfo[306]) {
                    var str = obj[k].exifInfo[306];
                    var str2 = str.split(' ');
                    str2[0] = str2[0].replace(/:/g, '/');
                    var shootDate = str2.join(' ');
                } else {
                    var lastMod = obj[k].lastModify;

                    var shootDate = lastMod;
                }
                singleFile.time = Date.parse(new Date(shootDate)) / 1000;
                nodes.push(singleFile);
            }
            postData.nodes = nodes;
            return postData;
        },
        zSinglePagePostdata: function (dragShuffle, dragId) {
            var self = this;
            var postData = {};
            postData.page_width = self._canvasInitWidth;
            postData.page_height = self._canvasInitHeight;
            postData.page_cell_gap = self._pageCellGap;
            postData.page_count = 1;
            postData.page_margin = self._pageMargin;
            var nodes = [];
            for (var i = 0; i < self._currentPageAlgo.length; i++) {

                var id = self._currentPageAlgo[i].id;
                var fileInfo = self._zAllFileInfo[id];

                console.log(id);
                console.log(self._zAllFileInfo);
                var singleFile = {};
                if (fileInfo.exifInfo && (fileInfo.exifInfo[274] == 6 || fileInfo.exifInfo[274] == 8 || fileInfo.exifInfo[274] == 5 || fileInfo.exifInfo[274] == 7)) {
                    singleFile.w = fileInfo.fileHeight;
                    singleFile.h = fileInfo.fileWidth;
                    // console.log(fileInfo.exifInfo[274], '1');
                } else {
                    singleFile.w = fileInfo.fileWidth;
                    singleFile.h = fileInfo.fileHeight;
                    // console.log(fileInfo.exifInfo[274], '1');

                }
                singleFile.id = id;
                nodes.push(singleFile);
            }
            if (dragShuffle) {
                if (self._currentPageAlgo.length < 6) {
                    var fileInfo = self._zAllFileInfo[dragId];
                    var singleFile = {};
                    if (fileInfo.exifInfo && (fileInfo.exifInfo[274] == 6 || fileInfo.exifInfo[274] == 8 || fileInfo.exifInfo[274] == 5 || fileInfo.exifInfo[274] == 7)) {
                        singleFile.w = fileInfo.fileHeight;
                        singleFile.h = fileInfo.fileWidth;
                        // console.log(fileInfo.exifInfo[274], '1');
                    } else {
                        singleFile.w = fileInfo.fileWidth;
                        singleFile.h = fileInfo.fileHeight;
                        // console.log(fileInfo.exifInfo[274], '1');

                    }
                    singleFile.id = dragId;
                    nodes.push(singleFile);

                } else {
                    layer.msg("There can't be more than 6 picturs in a page");
                }
            }
            postData.nodes = nodes;
            return postData;
        },
        zBoardRepaint: function (board, ctx, curAlgoAll, shuffling, dragging) {
            var self = this;
            var boardWidth = self._canvasInitWidth;
            var boardHeight = self._canvasInitHeight;

            console.log(boardWidth,boardHeight,'=============');

            self._canvas.clear();

            var totalAlgo = curAlgoAll.length;
            if (shuffling && !dragging) {
                self._cpAlgoIndex += 1;
                if (self._cpAlgoIndex >= curAlgoAll.length) {
                    self._cpAlgoIndex = 0;
                }
                console.log(self._cpAlgoIndex);
                var cellArray = curAlgoAll[self._cpAlgoIndex];
                console.log(cellArray);

                self._totalModuleAlgos.splice(self._currentModule - 1, 1, cellArray);

                var curModule = document.getElementById('LAY_bottom').getElementsByClassName('ifa_list_item')[this._currentModule - 1];
                var curCanvas = curModule.getElementsByTagName('canvas')[0];
                var curCtx = curCanvas.getContext('2d');
                curCtx.clearRect(0, 0, boardWidth, boardHeight);

            } else if (!shuffling && dragging) {
                var rndIndex = 0;
                var cellArray = curAlgoAll;
                self._totalModuleAlgos.splice(self._currentModule - 1, 1, cellArray);

                var curModule = document.getElementById('LAY_bottom').getElementsByClassName('ifa_list_item')[this._currentModule - 1];
                var curCanvas = curModule.getElementsByTagName('canvas')[0];
                var curCtx = curCanvas.getContext('2d');
                curCtx.clearRect(0, 0, boardWidth, boardHeight);
            } else {
                var rndIndex = 0;
                var cellArray = curAlgoAll;
            }

            self._currentPageAlgo = cellArray;

            // console.log(currentPageAlgo,'===========curAlgo===============');
            // console.log(curAlgoAll,'===========curAlgoAll===============');

            for (var m = 0; m < cellArray.length; m++) {
                // for (var n = 0; n < cellArray[m].length; n++) {
                (function (m) {
                    var cellInfo = cellArray[m];
                    var imgId = cellInfo.id;
                    // var imgUrl = URL.createObjectURL(zAllFileInfo[imgId].fileInfo);
                    var imgUrl = self._zAllFileInfo[imgId].thumbSrc;
                    var imgThumbUrl = self._zAllFileInfo[imgId].thumbSrc;
                    var posInfo = cellInfo.rt;
                    var posT = posInfo.t;
                    var posL = posInfo.l;
                    var posR = posInfo.r;
                    var posB = posInfo.b;
                    var imgHeight = (posB - posT);
                    var imgWidth = (posR - posL);

                    var img = new Image();
                    img.src = imgUrl;
                    var imgThumb = new Image();
                    imgThumb.src = imgThumbUrl;
                    // img.onload = function () {
                    // console.log(m);
                    new fabric.Image.fromURL(imgUrl, function (imgF) {
                        // imgF.setShadow({

                        // });
                        imgF.set({
                            width: imgWidth,
                            height: imgHeight,
                            left: posL,
                            top: posT,
                            stroke: 'white',
                            strokeWidth: self._pageBorder,
                            borderColor: 'blue',
                            borderScaleFactor: self._borderScale,
                            padding: 2,
                            dirty: true,
                            lockMovementX: true,
                            lockMovementY: true,
                            hasControls: false,
                            hasRotatePoint: false,
                            hasBorders: true,
                            selectable: true,
                            evented: true,
                            shadow: {
                                color: '#000',
                                // offsetX: 20,
                                // offsetY: 20,
                                blur: 18
                            }
                        });
                        imgF.toObject = (function (toObject) {
                            return function () {
                                return fabric.util.object.extend(toObject.call(this), {
                                    imgId: this.imgId,
                                    nodeIndex: this.nodeIndex
                                });
                            };
                        })(imgF.toObject);
                        imgF.imgId = imgId;
                        imgF.nodeIndex = m;
                        self._canvas.add(imgF);
                    });
                    // ctx.beginPath();
                    // ctx.drawImage(img, posL, posT, imgWidth, imgHeight);
                    // ctx.closePath();
                    if (shuffling || dragging) {
                        curCtx.beginPath();
                        curCtx.drawImage(imgThumb, posL / self._toModuleRate, posT / self._toModuleRate, imgWidth / self._toModuleRate, imgHeight / self._toModuleRate);
                        curCtx.closePath();
                    }
                    // }
                })(m);
                self._canvas.renderAll();
                // }
            }
        },
        curAlgoChange: function (index, placeIndex, idORindex) {
            var self = this;
            switch (placeIndex) {
                case 0:
                    self._currentPageAlgo.splice(index, 1);
                    break;
                case 1:
                    self._currentPageAlgo[index].id = idORindex;
                    break;
                case 2:
                    var rId = self._currentPageAlgo[index].id;
                    self._currentPageAlgo[index].id = self._currentPageAlgo[idORindex].id;
                    self._currentPageAlgo[idORindex].id = rId;
                    break;
                default:
                    break;
            }
            return self._currentPageAlgo;
        },
        domUseNumChange: function (domId, caseIndex) {
            var changeDom = $('#LAY_left .ifa_list_item[data-imgId=' + domId + ']');
            // console.log(changeDom, 'changeDom');
            var domNum = changeDom.attr('data-num') * 1;
            switch (caseIndex) {
                case 0:
                    domNum -= 1;
                    if (domNum == 1) {
                        changeDom.find('.useTag2').removeClass('useTag2').addClass('useTag1');
                    }
                    if (domNum == 0) {
                        changeDom.find('.useTag1').removeClass('useTag1').addClass('noUse');
                        changeDom.find('span').hide();
                    }
                    changeDom.attr('data-num', domNum);
                    changeDom.find('span').html(domNum);
                    break;
                case 1:
                    domNum += 1;
                    if (domNum == 1) {
                        changeDom.find('.noUse').removeClass('noUse').addClass('useTag1');
                        changeDom.find('span').show();
                    }
                    if (domNum >= 2) {
                        changeDom.find('.useTag1').removeClass('useTag1').addClass('useTag2');
                    }
                    changeDom.attr('data-num', domNum);
                    changeDom.find('span').html(domNum);
                    break;
                default:
                    break;
            }
        },
        zDragAndDel: function (caseIndex, dragImgId, target) {
            var self = this;
            switch (caseIndex) {
                case 0:
                    var nodeIndex = self._canvas.getActiveObject().nodeIndex;
                    var delId = self._canvas.getActiveObject().imgId;
                    self.curAlgoChange(nodeIndex, 0);
                    // canvas.getActiveObject().remove();
                    // zBoardRepaint(board, ctx, currentPageAlgo, false, true);
                    // domUseNumChang(delId, 0);
                    $.ajax({
                        url: self._toPostUrl,
                        type: 'post',
                        dataType: 'json',
                        data: JSON.stringify(self.zSinglePagePostdata(false)),
                        success: function (data) {
                            console.log('shuffle success');
                            var dataBack = JSON.parse(data);
                            console.log(dataBack);
                            self._currentPageAlgosAll = dataBack.pages;
                            if (dataBack.err) {
                                layer.msg('shuffle failed', dataBack.err, { icon: 5 });
                            } else {
                                self.zBoardRepaint(self._board, self._ctx, self._currentPageAlgosAll, true, false);
                                self.domUseNumChange(delId, 0);
                            }
                            self._firstShuffle = false;
                        },
                        error: function (err) {
                            console.log('err', err);
                        },
                        complete: function () {
                            console.log('shuffle complete');
                        }

                    })
                    break;
                case 1:
                    var nodeIndex = target.nodeIndex;
                    var originId = target.imgId;
                    var placeId = dragImgId;
                    self.curAlgoChange(nodeIndex, 1, placeId);
                    self.zBoardRepaint(self._board, self._ctx, self._currentPageAlgo, false, true);
                    self.domUseNumChange(originId, 0);
                    self.domUseNumChange(placeId, 1);
                    break;
                case 2:
                    var dragId = dragImgId;
                    $.ajax({
                        url: self._toPostUrl,
                        type: 'post',
                        dataType: 'json',
                        data: JSON.stringify(self.zSinglePagePostdata(true, dragId)),
                        success: function (data) {
                            console.log('shuffle success');
                            var dataBack = JSON.parse(data);
                            console.log(dataBack);
                            self._currentPageAlgosAll = dataBack.pages;
                            if (dataBack.err) {
                                layer.msg('shuffle failed', dataBack.err, { icon: 5 });

                            } else {
                                self.zBoardRepaint(self._board, self._ctx, self._currentPageAlgosAll, true, false);
                                self.domUseNumChange(dragId, 1);
                            }
                            self._firstShuffle = false;
                        },
                        error: function (err) {
                            console.log('err', err);
                        },
                        complete: function () {
                            console.log('complete');
                        }

                    })
                    break;
                default:
                    break;
            }
        },
        zClickModulesChange: function (dir) {
            var self = this;
            if (self._currentModule == 1) {
                switch (dir) {
                    case 0:
                        leftBtn.className = "ifa_arrow ifa_left_disabled";
                        break;
                    case 1:
                        break;
                    case 2:
                        self._currentModule += 1;
                        leftBtn.className = "ifa_arrow ifa_arrow_left";
                        break;
                }
            } else if (self._currentModule == self._totalModules) {
                switch (dir) {
                    case 0:
                        break;
                    case 1:
                        self._currentModule -= 1;
                        rightBtn.className = "ifa_arrow ifa_arrow_right";
                        break;
                    case 2:
                        rightBtn.className = "ifa_arrow ifa_right_disabled";
                        break;
                }
            } else {
                switch (dir) {
                    case 0:
                        break;
                    case 1:
                        self._currentModule -= 1;
                        if (self._currentModule == 1) {
                            leftBtn.className = "ifa_arrow ifa_left_disabled";
                        }
                        break;
                    case 2:
                        self._currentModule += 1;
                        // console.log(currentModule, totalModules);
                        if (self._currentModule == self._totalModules) {
                            rightBtn.className = "ifa_arrow ifa_right_disabled";
                        }
                        break;
                }
            }

            curNumSpan.innerHTML = self._currentModule;
            var curEle = document.querySelectorAll('.ifa_photo_bottom .ifa_list_item');
            for (var i = 0; i < curEle.length; i++) {
                if (curEle[i].getAttribute('data-moduleorder') == this._currentModule) {
                    curEle[i].style.background = "#666";
                } else {
                    curEle[i].style.background = "#4c4c4c";
                }
            }
            self.zBoardRepaint(self._board, self._ctx, self._totalModuleAlgos[self._currentModule - 1], false, false);
            self._currentPageAlgo = self._totalModuleAlgos[self._currentModule - 1];
            self._firstShuffle = true;
        },
        zClickModulesJump: function (num) {
            var self = this;
            self._currentModule = num;

            if (self._currentModule == 1) {
                leftBtn.className = "ifa_arrow ifa_left_disabled";
            } else if (self._currentModule == self._totalModules) {
                rightBtn.className = "ifa_arrow ifa_right_disabled";
            } else {
                leftBtn.className = "ifa_arrow ifa_arrow_left"
                rightBtn.className = "ifa_arrow ifa_arrow_right"
            }

            curNumSpan.innerHTML = self._currentModule;

            var curEle = document.querySelectorAll('.ifa_photo_bottom .ifa_list_item');
            for (var i = 0; i < curEle.length; i++) {
                if (curEle[i].getAttribute('data-moduleorder') == this._currentModule) {
                    curEle[i].style.background = "#666";
                } else {
                    curEle[i].style.background = "#4c4c4c";
                }
            }
            self.zBoardRepaint(self._board, self._ctx, self._totalModuleAlgos[self._currentModule - 1], false, false);
            self._currentPageAlgo = self._totalModuleAlgos[self._currentModule - 1];
            self._firstShuffle = true;

        },
        zCreateClass: function (tagname, classname) {
            var domEle = document.createElement(tagname);
            domEle.className = classname;
            return domEle;
        },
        zModuleRepaint: function (board, ctx, arr) {
            var self = this;
            var boardHeight = self._moduleCanvasHeight;
            var boardWidth = self._moduleCanvasHeight * self._initRate;

            ctx.clearRect(0, 0, boardWidth, boardHeight);
            ctx.fillStyle = "white";
            ctx.fillRect(0, 0, boardWidth, boardHeight);

            var cellArray = arr;
            // console.log(cellArray);
            for (var m = 0; m < cellArray.length; m++) {
                // for (var n = 0; n < cellArray[m].length; n++) {
                (function (m) {
                    var cellInfo = cellArray[m];
                    // console.log(cellInfo);
                    var imgId = cellInfo.id;
                    // var imgUrl=URL.createObjectURL(zAllFileInfo[imgId].fileInfo);;
                    var imgUrl = self._zAllFileInfo[imgId].thumbSrc;
                    var posInfo = cellInfo.rt;
                    var posT = posInfo.t / self._toModuleRate;
                    var posL = posInfo.l / self._toModuleRate;
                    var posR = posInfo.r / self._toModuleRate;
                    var posB = posInfo.b / self._toModuleRate;
                    var imgHeight = posB - posT;
                    var imgWidth = posR - posL;

                    var img = new Image();
                    img.src = imgUrl;
                    img.onload = function () {
                        ctx.beginPath();
                        ctx.drawImage(img, posL, posT, imgWidth, imgHeight);
                        ctx.closePath();
                    }
                })(m);
                // }
            }
        },
        zCreateModules: function (data) {
            var self = this;
            var atr = data.pages;
            self._totalModuleAlgos = atr;
            self._totalModules = atr.length;
            curNumSpan.innerHTML = self._currentModule;
            totalNumSpan.innerHTML = self._totalModules;
            for (var i = 0; i < atr.length; i++) {
                (function (i) {
                    var orderNum = i + 1;
                    var moduleItem = self.zCreateClass('li', 'ifa_list_item');
                    var boardBox = document.createElement('div');
                    var moduleBoard = document.createElement('canvas');
                    var orz = moduleBoard.getContext('2d');

                    moduleItem.setAttribute('data-moduleorder', orderNum);

                    moduleBoard.width = self._canvasInitWidth / self._toModuleRate;
                    moduleBoard.height = self._canvasInitHeight / self._toModuleRate;
                    var pageArr = atr[i];

                    // 使导出的图片具有白背景
                    self.zModuleRepaint(moduleBoard, orz, pageArr);

                    var moduleInfo = document.createElement('p');
                    moduleInfo.innerHTML = (orderNum >= 10) ? orderNum : ('0' + orderNum);

                    boardBox.appendChild(moduleBoard);
                    moduleItem.appendChild(boardBox);
                    moduleItem.appendChild(moduleInfo);

                    zBottomContent.appendChild(moduleItem);

                    moduleItem.addEventListener('click', function () {
                        var that = this;
                        self.zClickModulesJump(that.getAttribute('data-moduleorder') * 1);
                    });


                })(i);
            }
            self.zClickModulesChange(0);
            /*横向滚动代码*/
            (function ($) {

                $("#LAY_bottom").mCustomScrollbar({
                    horizontalScroll: true,
                    scrollInertia: 0
                });
            })(jQuery);
        },
        zFirstGetAllModule: function (selectedFiles) {
            var self = this;
            var zFirstFilesInfo = self.infoToDic(selectedFiles);

            for (var k in zFirstFilesInfo) {
                if (self._keyNum < self._pageCount * 6) {
                    self.appendToLeft(k, zFirstFilesInfo[k], true);
                    self._zAllFileInfoToPost[k] = zFirstFilesInfo[k];
                } else if (self._keyNum == self._pageCount * 6) {
                    self.appendToLeft(k, zFirstFilesInfo[k], false);
                    layer.msg('the photo num is out of limit,we will choose the primary 120 photos to create the Modules');
                    // zAllFileInfoToPost[k]=zAllFileInfo[k];
                } else {
                    self.appendToLeft(k, zFirstFilesInfo[k], false);
                }
                self._keyNum += 1;
            }

            $('#ifa_zsj_photoNum').html(self._keyNum);

            board.width=self._canvasInitWidth;
            board.height=self._canvasInitHeight;            

            self._canvas = new fabric.Canvas('ifa_zsj_board');
            //canvas.setDimensions({ width: window.positionWidth * 0.7 + "px", height: window.positionWidth * 0.7 / 2 + "px", margin: "0 auto" }, { cssOnly: true });
            self._canvas.setDimensions({
                width: window.positionHeight * 0.6 * self._initRate + "px",
                height: window.positionHeight * 0.6 + "px",
                display: 'inline-block'
            }, { cssOnly: true });
            self._canvas.hoverCursor = 'default';

            self._canvas.on('mouse:down', function (e) {
                if (e.target != null) {
                    self._isCanvasReplace = true;
                    console.log('move');
                    self._replaceImg = e.target;
                } else {
                    self._isCanvasReplace = false;
                }
            })
            self._canvas.on('mouse:up', function (e) {
                if (self._isCanvasReplace) {
                    if (e.target != null && e.target != self._replaceImg) {
                        self.curAlgoChange(e.target.nodeIndex, 2, self._replaceImg.nodeIndex);
                        self.zBoardRepaint(self._board, self._ctx, self._currentPageAlgo, false, true);
                        self._firstShuffle = true;
                    }
                    self._isCanvasReplace = false;
                }
            })
            console.log(self.zAllInfoToPostdata(self._zAllFileInfoToPost));
            $.ajax({
                url: self._toPostUrl,
                contentType: "application/json; charset=utf-8",
                type: 'post',
                dataType: 'json',
                data: JSON.stringify(self.zAllInfoToPostdata(self._zAllFileInfoToPost)),
                success: function (data) {
                    console.log('totalAjax success');

                    var dataBack = JSON.parse(data);
                    console.log(dataBack);
                    if (dataBack.err) {
                        layer.msg('create failed,something wrong with the paramer', { icon: 5 });

                    } else {
                        self.zCreateModules(dataBack);
                        $('#ifa_load_page').hide();
                        $('#ifa_complete_page').show();
                        setTimeout(function () {
                            $('.ifa_content').css('visibility', 'visible');
                            $('#ifa_complete_page').hide();
                        }, 3000)
                    }
                },
                error: function (err) {
                    console.log('err', err);
                },
                complete: function () {
                    console.log('complete');
                }

            })
        },
        zAddListener: function () {
            var self = this;
            // ================左右切换以及shuffle事件==============
            $('.ifa_photo_beautify').click(function () {
                if (self._firstShuffle) {
                    console.log('firstShuffle');
                    $.ajax({
                        url: self._toPostUrl,
                        type: 'post',
                        dataType: 'json',
                        data: JSON.stringify(self.zSinglePagePostdata(false)),
                        success: function (data) {
                            console.log('shuffle success');
                            var dataBack = JSON.parse(data);
                            console.log(dataBack);
                            self._currentPageAlgosAll = dataBack.pages;
                            if (dataBack.err) {
                                layer.msg('shuffling failed', dataBack.err, { icon: 5 });

                            } else {
                                self.zBoardRepaint(self._board, self._ctx, self._currentPageAlgosAll, true, false);
                            }
                            self._firstShuffle = false;
                        },
                        error: function (err) {
                            console.log('err', err);
                        },
                        complete: function () {
                            console.log('complete');
                        }

                    })
                } else {
                    console.log('not firstShuffle');
                    self.zBoardRepaint(self._board, self._ctx, self._currentPageAlgosAll, true, false);
                }
                console.log(self);
                console.log(self.zTotalInfoExport(self._totalModuleAlgos));
            });
            $('.ifa_arrow_left').click(function () {
                self.zClickModulesChange(1);
                $('#LAY_bottom').mCustomScrollbar("scrollTo", '.ifa_list_item[data-moduleorder=' + self._currentModule + ']');
            })
            $('.ifa_arrow_right').click(function () {
                self.zClickModulesChange(2);
                $('#LAY_bottom').mCustomScrollbar("scrollTo", '.ifa_list_item[data-moduleorder=' + self._currentModule + ']');
                // mover()
            })

            // =========================左侧图片栏移除事件=================
            $('.ifa_list_tree').on('click', '.ifa_list_item a', function () {
                if ($(this).parent('.ifa_list_item').attr('data-num') > 0) {
                    layer.msg("the picture is using in the right so you can't delete it!");
                } else {
                    self._keyNum -= 1;
                    var fileId = $(this).parent('.ifa_list_item').attr('data-imgId');
                    delete self._zAllFileInfo[fileId];
                    $(this).parent('.ifa_list_item').remove();
                    $('#ifa_zsj_photoNum').html(self._keyNum);
                }
            })

            // ========================添加拖拽事件===================
            $('#LAY_left').ready(function () {
                $(this).on('dragstart', '.ifa_list_item', function () {
                    // console.log($(this));
                    self._curDragDom = $(this);
                    self._curDragDomImgId = $(this).attr('data-imgId');
                    self._curDragDomUse = $(this).attr('data-num');
                })
            })

            $('.ifa_photo_canvas').on('dragover', '.canvas-container', function (e) {
                e.preventDefault();
            })
            $(document).on('drop', function (e) {
                var dropToDom = $('.upper-canvas');
                console.log(e.target, '================');
                if (e.target == dropToDom[0]) {
                    e.preventDefault();
                    self._isDragging = true;
                    self._canvas.on('mouse:over', function (e) {
                        if (self._isDragging) {
                            self._firstShuffle = true;
                            if (e.target != null) {
                                // curAlgoChange(e.target.imgId, true, curDragDomImgId);
                                // zBoardRepaint(board, ctx, currentPageAlgo, false, true);
                                self.zDragAndDel(1, self._curDragDomImgId, e.target);
                            } else {
                                self.zDragAndDel(2, self._curDragDomImgId);
                            }
                            self._canvas.off('mouse:over');
                            self._isDragging = false;
                        }
                    })
                } else {
                    self._isDragging = false;
                }
            })

            // ====================添加删除事件===================
            document.onkeyup = function (event) {
                var e = event || window.event;
                var keyCode = e.keyCode || e.which;
                switch (keyCode) {
                    case 8:
                        if (self._canvas.getActiveObject()) {
                            if (self._canvas.toObject().objects.length > 1) {
                                self.zDragAndDel(0);
                            } else {
                                layer.msg('There must be more than 1 picture in a page');
                            }
                        } else {
                            layer.msg('Choose a picture first');
                        }
                        break;
                    case 46:
                        if (self._canvas.getActiveObject()) {
                            if (self._canvas.toObject().objects.length > 1) {
                                self.zDragAndDel(0);
                            } else {
                                layer.msg('There must be more than 1 picture in a page');
                            }
                        } else {
                            layer.msg('Choose a picture first');
                        }
                        break;
                    default:
                        // layer.msg('You can press down the Delete Key to delete the picture in the canvas');
                        break;
                }
            }
        },
        zTotalInfoExport: function (arr) {
            var self = this;
            var totalInfo = {};
            totalInfo.productId = self._productId;
            totalInfo.pageBorder = self._pageBorder;
            totalInfo.pageTitle = window.albumTitle;
            totalInfo.pageWidth = self._canvasInitWidth;
            totalInfo.pageHeight = self._canvasInitHeight;
            totalInfo.pageCellGap = self._pageCellGap;
            totalInfo.pageMargin = self._pageMargin;
            var pages = [];
            for (var i = 0; i < arr.length; i++) {
                var arrPage = arr[i];
                var page = [];
                for (var n = 0; n < arrPage.length; n++) {
                    var node = {};
                    var tId = arrPage[n].id;
                    var tInfo = self._zAllFileInfo[tId];
                    var rt = arrPage[n].rt;
                    node.fileId = tId;
                    node.top = rt.t;
                    node.left = rt.l;
                    node.bottom = rt.b;
                    node.right = rt.r;
                    node.width = tInfo.fileWidth;
                    node.height = tInfo.fileHeight;
                    node.type = tInfo.fileType;
                    node.size = tInfo.fileSize;
                    node.zIndex = n;
                    if (tInfo.exifInfo && tInfo.exifInfo[306]) {
                        var str = tInfo.exifInfo[306];
                        var str2 = str.split(' ');
                        str2[0] = str2[0].replace(/:/g, '/');
                        var shootDate = str2.join(' ');
                    } else {
                        var lastMod = tInfo.lastModify;

                        var shootDate = lastMod;
                    }
                    node.time = Date.parse(new Date(shootDate)) / 1000;
                    if (tInfo.exifInfo && tInfo.exifInfo[274]) {
                        node.rotate = tInfo.exifInfo[274];
                    } else {
                        node.rotate = 1;
                    }

                    page.push(node);

                }

                pages.push(page);

            }
            totalInfo.pages = pages;
            return totalInfo;
        }
    }
    window.Zeditor = Zeditor;
})();